package com.fosung.frame.modules.sys.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fosung.frame.common.config.Global;
import com.fosung.frame.common.web.BaseController;

@Controller
@RequestMapping(value = "${adminPath}/file")
public class FileController extends BaseController {
	
	private  String down_driver_path = Global.getConfig("down_driver_path");;
	
	@RequestMapping(value = "/downLoadCardDriver", method = RequestMethod.POST)
	public  void fileDownLoad(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String filePath = down_driver_path;
		if (response != null && request != null && filePath != null
				&& !filePath.equals("")) {
			// filePath是指欲下载的文件的路径。
			filePath = URLDecoder.decode(filePath, "UTF-8");
			File file = new File(filePath);
			if (!file.exists()) {
				throw new Exception("文件不存在！");
			}
			if (!file.isFile()) {
				throw new Exception("非文件类型！");
			}

			// 取得文件名。
			String fileName = file.getName();
			// 提示框设置
			response.reset(); // reset the response
			// response.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream");// 告诉浏览器输出内容为流
			response.setHeader("content-disposition", "attachment; filename=\""
					+ fileName + "\"");

			// 读出文件到i/o流
			FileInputStream fis = new FileInputStream(file);
			BufferedInputStream buff = new BufferedInputStream(fis);
			byte[] ary_byte = new byte[10240];// 缓存
			long k = 0;// 该值用于计算当前实际下载了多少字节
			// 输出流
			OutputStream out = response.getOutputStream();
			// 开始循环下载
			while (k < file.length()) {
				int j = buff.read(ary_byte, 0, 10240);
				k += j;
				// 将b中的数据写到客户端的内存
				out.write(ary_byte, 0, j);
			}
			// 关闭输出流
			if (out != null) {
				out.flush();
				out.close();
				fis.close();
				buff.close();
			}
		} else {
			new NullPointerException(
					"HttpServletRequest Or HttpServletResponse Or fileName Is Null !");
		}
		
	}
}
